import { useEffect, useRef, useState, KeyboardEvent, MouseEvent, useCallback } from "react";
import { Form } from 'antd';

import { request } from "@yaf/request";
import { EnumRouter } from "@/constants";
import { RespDataType, login, getCaptchaImage } from "./api";
import BGParticle from "./BGParticle";
import BgImg from "./img/bg.png";


export const useLogin = () => {
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [captchaImageInfo, setCaptchaImageInfo] = useState<RespDataType.ICaptchaImageInfo>({
    img: "",
    key: ""
  });
  const [form] = Form.useForm();
  const canvasRef = useRef<HTMLCanvasElement>();

  useEffect(() => {
    if (!loading) {
      const particle = new BGParticle(canvasRef.current);
      particle.init();
      return () => {
        particle.destroy();
      }
    }
  }, [loading]);

  useEffect(() => {
    const handleLoadImage = () => setLoading(false);
    loadImageAsync(BgImg).then(handleLoadImage).catch(handleLoadImage);
    fetchCaptchaImage();
  }, []);

  // 获取验证码图片
  const fetchCaptchaImage = useCallback(() => {
    getCaptchaImage().then((resp) => {
      // resp.data.img = "data:image/png;base64,"+resp.data.img
      setCaptchaImageInfo(resp.data);
    })
  }, [])

  const handleSubmit = (e?: KeyboardEvent<HTMLInputElement> | MouseEvent<HTMLElement>) => {
    e = e as KeyboardEvent<HTMLInputElement>;
    if (e.type == "click" || (e.code && e.code.toLocaleLowerCase() == "enter")) {
      setSubmitting(true);
      form.validateFields().then((resp) => {
        const { loginName, password, code } = resp;
        login({ loginName, password, verifyCode: code, verifyKey: captchaImageInfo.key }).then((resp) => {
          // 1. 保存请求token
          request.setToken(resp.data.token);

          window.location.href = EnumRouter.appRoot;
          setSubmitting(false);
        }).catch((e) => {
          if (e.code == 50) fetchCaptchaImage()
          setSubmitting(false)
        });

      }).catch(() => {
        setSubmitting(false)
      })
    }
  }

  return { loading, submitting, BgImg, canvasRef, handleSubmit, form, captchaImageInfo, fetchCaptchaImage }
}

const loadImageAsync = (url: string) => {
  return new Promise((resolve, reject) => {
    const image = new Image();
    image.onload = () => {
      resolve(url);
    };
    image.onerror = () => {
      console.error('图片载入错误')
      reject();
    };
    image.src = url;
  });
}
